import 'dart:convert';

import 'package:appflutterhomeschool/api/api_service.dart';
import 'package:appflutterhomeschool/api/dio_utils.dart';
import 'package:appflutterhomeschool/common/common.dart';
import 'package:appflutterhomeschool/model/form_switch_model.dart';
import 'package:appflutterhomeschool/model/student_information_model.dart';
import 'package:appflutterhomeschool/utils/sp_util.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';

import '../my_app_view_model.dart';

///用户： ninetailedfox
///时间： 2020/6/14
///邮箱： 1037438704@qq.com
///功能： 班级管理   状态管理

class SwitchClassesViewModel extends ChangeNotifier {
  TextEditingController textEditingController = TextEditingController();

  BuildContext me;
  List<StudentInformationModel> studentList = [];

  List<FormSwitchModel> gridList = [
    FormSwitchModel("爸爸",
        imageUrl: "baba", judge: true, imageUrlFalse: "baba_false"),
    FormSwitchModel("妈妈",
        imageUrl: "mama", judge: false, imageUrlFalse: "mama_false"),
    FormSwitchModel("爷爷",
        imageUrl: "yeye", judge: false, imageUrlFalse: "yeye_false"),
    FormSwitchModel("奶奶",
        imageUrl: "nainai", judge: false, imageUrlFalse: "nainai_false")
  ];

  bool identity;

  SwitchClassesViewModel(this.me);

  MyAppViewModel myAppViewModel;

  initView() {
    studentList.clear();
    myAppViewModel = Provider.of<MyAppViewModel>(me);
    //true 是老师  false 是家长
    identity = myAppViewModel.identity;
    if (identity) {
      DioUtils.getInstance()
          .post(ApiService.getSubjects, {"token": Constant.getToken()},
              (successCallBack) {
        gridList.clear();
        (successCallBack["data"]["subject_list"] as List).forEach((element) {
          DioUtils.getInstance()
              .post(ApiService.getSubjectIcon, {"id": element["id"]},
                  (successCallBack) {
            if (successCallBack['data'] == null) {
              return;
            }
            gridList.add(FormSwitchModel(element["name"],
                imageUrl: successCallBack["data"]["subject_icon"]["icon"] ?? "",
                imageUrlFalse:
                    successCallBack["data"]["subject_icon"]["false_icon"] ?? "",
                judge: false,
                fileAndUrl: 1));
          }, (errorCallBack) {});
        });
        notifyListeners();
      }, (errorCallBack) {
        Fluttertoast.showToast(msg: errorCallBack);
      });
      //获取班级列表
      DioUtils.getInstance().post(ApiService.getClasses, {
        "token": Constant.getToken(),
      }, (successCallBack) {
        (successCallBack["data"]["class_list"] as List).forEach((element) {
          studentList.add(StudentInformationModel.fromJson(identity, element));
        });
//        for (int i = 0; i < studentList.length; i++) {
//          DioUtils.getInstance()
//              .post(ApiService.getSubjectIcon, {"id": studentList[i]?.subjectId},
//                  (successCallBack) {
//                if (successCallBack["data"] == null) {
//                  return;
//                }
//                studentList[i].imageUrl = successCallBack["data"]["subject_icon"]["icon"];
//                studentList[i].imageUrlFalse = successCallBack["data"]["subject_icon"]["false_icon"];
//              }, (errorCallBack) {});
//        }
        notifyListeners();
      }, (errorCallBack) {
        Fluttertoast.showToast(msg: errorCallBack);
      });
    } else {
      //获取学生列表
      DioUtils.getInstance().post(ApiService.getStudents, {
        "token": Constant.getToken(),
      }, (successCallBack) {
        (successCallBack["data"]["students"] as List).forEach((element) {
          studentList.add(StudentInformationModel.fromJson(identity, element));
        });

        for (int i = 0; i < studentList.length; i++) {
          DioUtils.getInstance()
              .post(ApiService.getSubjectIcon, {"id": studentList[i]?.subjectId},
                  (successCallBack) {
                if (successCallBack["data"] == null) {
                  return;
                }
                studentList[i].imageUrl = successCallBack["data"]["subject_icon"]["icon"];
                studentList[i].imageUrlFalse = successCallBack["data"]["subject_icon"]["false_icon"];
              }, (errorCallBack) {});
        }


        notifyListeners();
      }, (errorCallBack) {
        Fluttertoast.showToast(msg: errorCallBack);
      });
    }
  }

  //选择班级或者学生
  switchOnTap(int index) {
    if (identity) {
      DioUtils().post(ApiService.updateClsNow, {
        "token": Constant.getToken(),
        "cls_mapping_id": studentList[index].classMappingId,
      }, (successCallBack) {
        studentList[index].choice = true;
        notifyListeners();
        SpUtil.putString("getStudent", jsonEncode(studentList[index].toJson())).then((value){
          myAppViewModel.initView();
          myAppViewModel.refresh();
          Navigator.pop(me);
        });
      }, (errorCallBack) {});
    } else {
      DioUtils().post(ApiService.updateStudentNow, {
        "token": Constant.getToken(),
        "student_id": studentList[index].subjectId,
      }, (successCallBack) {
        studentList[index].choice = true;
        notifyListeners();
        SpUtil.putString("getStudent", jsonEncode(studentList[index].toJson())).then((value){
          if(value){
            Navigator.pop(me);
            myAppViewModel.initView();
            myAppViewModel.refresh();
          }
        });
      }, (errorCallBack) {});
    }
  }
}
